import 'dart:io';

import 'package:adb_tool/base/base_view_model.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:process_run/shell.dart';

import '../../common/app.dart';
import '../../common/selector_plus.dart';
import 'media_model.dart';

class MediaManagementViewModel extends BaseViewModel {
  String deviceId;
  String packageName;
  String currentPath = '/sdcard/';
  SelectorListPlusData<MediaModel> files = SelectorListPlusData();

  MediaManagementViewModel(BuildContext context, this.deviceId, this.packageName) : super(context) {
    App().eventBus.on<DeviceIdEvent>().listen((event) {
      deviceId = event.deviceId;
    });
    App().eventBus.on<PackageNameEvent>().listen((event) {
      packageName = event.packageName;
    });
  }

  init() async {
    adbPath = await App().getAdbPath();
    await getFileList();
  }

  getFileList() async {
    files.value = [];
    showLoading(text: "图片检索中");
    var savePath = ((await getApplicationSupportDirectory()).path) + "/$deviceId-images";
    await folderExists(savePath);
    await Directory(savePath).list().forEach((element) {
      var value = element.path;
      if (_isImage(value)) {
        files.add(MediaModel(value, false, DateTime.now().millisecondsSinceEpoch));
      }
    });
    dismissLoading();
    notifyListeners();
    await traversal(currentPath, files.value.isEmpty);
    notifyListeners();
  }

  folderExists(String filepath) async {
    var file = Directory(filepath);
    try {
      bool exists = await file.exists();
      if (!exists) {
        await file.create();
      }
    } catch (e) {
      print(e);
    }
  }

  /// 遍历文件夹
  Future<void> traversal(String filePath, bool isShowLoading) async {
    var savePath = ((await getApplicationSupportDirectory()).path) + "/$deviceId-images";
    await folderExists(savePath);
    debugPrint("打开路径=" + filePath);
    var result = await execAdb(["-s", deviceId, "shell", "ls", "-F", filePath], isShowLoading: isShowLoading);
    if (result == null) return;
    for (var value in result.outLines) {
      if (value.endsWith("/")) {
        if (_isContinueFile(value)) {
          continue;
        } else {
          var path = filePath + value;
          traversal(path, isShowLoading);
        }
      } else {
        if (_isImage(value)) {
          var currentImage = savePath + "/$value";
          bool exists = await File(currentImage).exists();
          if (!exists) {
            await saveFile(filePath + value, currentImage);
            files.add(MediaModel(currentImage, false, DateTime.now().millisecondsSinceEpoch));
            notifyListeners();
          }
        }
      }
    }
  }

  /// 判断是否是图片
  bool _isImage(String value) {
    return value.endsWith(".jpg") ||
        value.endsWith(".png") ||
        value.endsWith(".PNG") ||
        value.endsWith(".jpeg") ||
        value.endsWith(".JPEG");
  }

  /// 忽略的扫描文件
  bool _isContinueFile(String value) {
    return value == "Android/" || value == "Notifications/" || value == "MIUI/";
  }

  /// 保存文件
  Future<void> saveFile(String path, String savePath) async {
    debugPrint("图片路径：" + path + ";;;保存的路径：" + savePath);
    var result = await execAdb(["-s", deviceId, "pull", path, savePath]);
    // if (result != null && result.exitCode == 0) {
    //   showResultDialog(content: "保存成功");
    // } else {
    //   showResultDialog(content: "保存失败");
    // }
  }
}
